import { Scene, type ISceneConfig } from "@antv/l7";

/**
 *  场景配置
 */
export interface SceneConfig extends ISceneConfig {
    /** 场景 id */
    id: string;
}

/**
 * 场景状态
 */
export interface SceneState {
    /** 场景 id */
    id: string;
    /** 场景是否已初始化 */
    inited: boolean;
}

/**
 * 地图场景
 */
export class MapScene implements SceneState {
    readonly id: string;
    config: SceneConfig;
    inited: boolean = false;
    protected scene?: Scene = undefined;

    /**
     * 构造函数
     * @param config 场景配置
     * @param id     场景 id
     */
    constructor(config: SceneConfig) {
        this.id = config.id;
        this.config = config;
        return this;
    }
    /**
     * 初始化场景
     */
    async init(): Promise<MapScene> {
        if (this.scene) {
            return this;
        }
        return new Promise((resolve) => {
            this.scene = new Scene(this.config);
            this.scene.on("loaded", () => {
                this.inited = true;
                resolve(this);
            });
        });
    }
    /**
     * 销毁场景
     */
    destroyScene() {
        if (this.scene) {
            this.scene.destroy();
        }
        this.scene = undefined;
        this.inited = false;
    }
    /**
     * 获取场景状态
     */
    getState(): SceneState {
        return {
            id: this.id,
            inited: this.inited
        };
    }
    /**
     * 获取场景实例 若未找到则报错
     * @returns 场景实例
     */
    getInstance(): Scene {
        if (!this.scene) {
            throw new Error("Scene is not initialized");
        }
        return this.scene;
    }
    /**
     * 尝试获取场景实例，若未找到则返回 undefined
     */
    tryGetInstance(): Scene | undefined {
        return this.scene;
    }
    /**
     * 获取当前视口的 bbox
     */
    getViewBbox(): [[number, number], [number, number]] {
        return this.getInstance().getBounds();
    }
}
